package co.com.javeriana.aes.oms.ejb.orders.service;

import co.com.javeriana.aes.oms.common.entity.Campaign;
import co.com.javeriana.aes.oms.common.entity.Customer;
import co.com.javeriana.aes.oms.common.entity.Items;
import co.com.javeriana.aes.oms.common.entity.Orders;
import co.com.javeriana.aes.oms.ejb.orders.dto.CampaignDTO;
import co.com.javeriana.aes.oms.ejb.orders.dto.Item;
import co.com.javeriana.aes.oms.ejb.orders.dto.Order;
import co.com.javeriana.aes.oms.ejb.orders.dto.OrderStatus;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;

/**
 *
 * @author Jonathan Fernandez <jonathan.fvargas@gmail.com>
 */
@WebService(serviceName = "Orders")
@Stateless()
public class OrdersWebService {

    @EJB
    private OrdersServiceBeanLocal localservice;
    
    
    /**
     * 
     * @param costumerID
     * @return 
     */
    @WebMethod(operationName = "findOrderByCustomerId")
    public List<Order> findOrderByCustomerId(@WebParam(name = "cosumerID") int costumerID) {
        
        List<Order> dtoOrders = new ArrayList<Order>();
        
        try {
            
            List <Orders> entityOrders = localservice.findOrderByCustomerId(costumerID);
            List <Item> itemsDTO = new ArrayList<Item>();
            for (Orders order : entityOrders) {
                 
                 Order dtoOrder = new Order();
                 dtoOrder.setComments(order.getComments());
                 dtoOrder.setCostumerID(order.getCustomerCusid().getCusid());
                 dtoOrder.setOrderDate(order.getOrderdate());
                 dtoOrder.setOrderID(order.getOrdid());
                 dtoOrder.setPrice(order.getPrice().floatValue());
                 dtoOrder.setStatus(OrderStatus.valueOf(order.getStatus()));
                 
                 for (Items i : order.getItemsList()){
                     Item itemDTO = new Item();
                     itemDTO.setItemId(i.getItemid());
                     itemDTO.setOrderId(order.getOrdid());
                     itemDTO.setPartNumber(i.getPartnum());
                     itemDTO.setPeriod(i.getProdid());
                     itemDTO.setPrice(i.getPrice().floatValue());
                     itemDTO.setProductId(i.getProdid());
                     itemDTO.setProductName(i.getProductname());
                     itemDTO.setQuantity(i.getQuantity());
                     itemsDTO.add(itemDTO);
                 }
                 
                 dtoOrder.setItems(itemsDTO);
                 //add to return list
                 dtoOrders.add(dtoOrder);
            }
            
        } catch (Exception ex) {
            Logger.getLogger(OrdersWebService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return dtoOrders;
    }    
   
    
    /**
     * 
     * @param orderID
     * @param status
     * @return 
     */
    @WebMethod(operationName = "updateOrderStatus")
    public boolean updateOrderStatus(@WebParam(name = "orderID") int orderID, @WebParam(name = "status") OrderStatus status) {        
        
        boolean action = false;
        
        try {
            
            Orders order = localservice.getOrder(orderID);
            order.setStatus(status.name());
            localservice.updateOrder(order);
            action = true;                    
        } catch (Exception e) {            
            action = false;
            e.printStackTrace();
        }
        return action;
    }    

    /**
     *
     * @param orderID
     * @return
     */
    @WebMethod(operationName = "CancelOrder")
    public boolean CancelOrder(@WebParam(name = "orderID") int orderID) {

        Orders entityOrder = null;

        try {
            entityOrder = localservice.findOrderByID(orderID);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //editar en Bolivariano 
        //llamar a avianca
        //llamar a american air lines
        //llamar a hilton        
        //llamar a servicio de dan carton
        //dymmy
        Random rnd = new Random();
        return rnd.nextBoolean();
    }

    /**
     * 
     * @param order
     * @return 
     */
    @WebMethod(operationName = "createOrder")
    public Integer createOrder(@WebParam(name = "order") Order order) {
       
        Orders entityOrder = new Orders();
        Integer orderID = null;
        try {

            entityOrder.setComments(order.getComments());
            Customer c = localservice.getCustomer(order.getCostumerID());
            entityOrder.setCustomerCusid(c);
            entityOrder.setOrderdate(order.getOrderDate());
            //entityOrder.setOrdid(order.getOrderID());
            entityOrder.setPrice(BigDecimal.valueOf(order.getPrice()));
            //TODO : revisar el entity si vale la pena colocarle el enum
            entityOrder.setStatus( order.getStatus().name() );

            List<Items> entityItems = new ArrayList<Items>();

            for (Item i : order.getItems()) {
                Items items = new Items();
                //items.setItemid(i.getItemId());
                items.setPartnum(i.getPartNumber());
                items.setPrice(BigDecimal.valueOf(i.getPrice()));
                items.setProdid(i.getProductId());
                items.setProductname(i.getProductName());
                items.setQuantity(i.getQuantity());
                //Orders o = localservice.findOrderByID();
                items.setOrdersOrdid(entityOrder);
                entityItems.add(items);
            }

            entityOrder.setItemsList(entityItems);

            orderID = localservice.createOrder(entityOrder, entityItems);
        } catch (Exception ex) {
            Logger.getLogger(OrdersWebService.class.getName()).log(Level.SEVERE, null, ex);
        }

        return orderID;
    }

    /**
     * This is a sample web service operation
     *
     * @param costumerID
     * @param status
     * @return
     */
    @WebMethod(operationName = "findOrder")
    public List<Order> findOrder(@WebParam(name = "cosumerID") int costumerID, @WebParam(name = "state") OrderStatus status) {

        return null;

    }

    /**
     *
     * @param orderID
     * @return
     */
    @WebMethod(operationName = "FindOrderByID")
    public Order FindOrderByID(@WebParam(name = "orderID") int orderID) {


        Orders entityOrder = null;
        Order order = null;
        try {
            entityOrder = localservice.findOrderByID(orderID);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (entityOrder != null) {

            order = new Order();
            order.setComments(entityOrder.getComments());
            order.setCostumerID(entityOrder.getCustomerCusid().getCusid());

            List<Item> items = new ArrayList<Item>();
            for (co.com.javeriana.aes.oms.common.entity.Items entityItem : entityOrder.getItemsList()) {

                Item item = new Item();
                item.setItemId(entityItem.getItemid());
                item.setOrderId(entityItem.getOrdersOrdid().getOrdid());
                item.setPartNumber(entityItem.getPartnum());
                item.setPeriod(entityItem.getProdid());
                item.setPrice(entityItem.getPrice().floatValue());
                item.setProductId(entityItem.getProdid());
                item.setProductName(entityItem.getProductname());
                item.setQuantity(entityItem.getQuantity());
                items.add(item);
            }

            order.setItems(items);
            order.setOrderDate(entityOrder.getOrderdate());
            order.setPrice(entityOrder.getPrice().floatValue());
            order.setStatus(OrderStatus.valueOf(entityOrder.getStatus()));

        }
        return order;

    }

    
    private List <Integer> getRamdom(int ramdom){        
        List <Integer> aa = new ArrayList<Integer>();
          Random rnd = new Random();
          int range = 1000000 - 1 + 1;
        for (int i = 0; i<ramdom; i++){            
            aa.add( rnd.nextInt(range) + 1);
            
        }
        return aa;
    }
    
    /**
     * 
     * @return 
     */
    @WebMethod(operationName = "getCampaigns")
    public List<CampaignDTO> getCampaigns() {

        List<Campaign> camEntity = this.localservice.getCampaigns();
        List<CampaignDTO> campaignsDTOS = new ArrayList<CampaignDTO>();        
        Random rn = new Random();
        int range = 4 - 3 + 1;
        int randomNum =  rn.nextInt(range) + 3;
        
        for (Campaign entity : camEntity) {
            CampaignDTO dto = new CampaignDTO();
            dto.setDescription(entity.getDescription());
            dto.setID(entity.getId());
            dto.setImage(entity.getImage());
            dto.setName(entity.getName());
            dto.setProducID(getRamdom(randomNum));            
            campaignsDTOS.add(dto);
        }
        return campaignsDTOS;
    }
    
   /**
    * Servicio que permite retornar el Top 5 de productos mas vendidos relacionados con el producto identificado
    * @param idProduct Idetificador del producto seleccionado
    * @return List de Productos deo Top5 ordenados de mayor a menor
    */
    @WebMethod(operationName = "getTopFiveProducts")
    public List<Integer> getTopFiveProducts(int idProduct) {
        List<Integer> products = null;
        try {
            products = this.localservice.getTopFiveProducts(idProduct);
        } catch (Exception ex) {
             ex.printStackTrace();
        }
        return products;
    }
    
    
      /**
    * Servicio que permite retornar el Top de productos mas vendidos relacionados con el producto identificado
    * @return List de Productos deo Top5 ordenados de mayor a menor
    */
    @WebMethod(operationName = "getTopProducts")
    public List<Integer> getTopProducts() {
        List<Integer> products = null;
        try {
            products = this.localservice.getTopProducts();
        } catch (Exception ex) {
             ex.printStackTrace();
        }
        return products;
    }
    
      /**
    * Servicio que permite retornar el Top de productos mas vendidos relacionados con el producto identificado
    * @return List de Productos deo Top5 ordenados de mayor a menor
    */
    @WebMethod(operationName = "getTopOpenOrders")
    public List<Integer> getTopOpenOrders() {
        List<Integer> products = null;
        try {
            products = this.localservice.getTopOpenOrders();
        } catch (Exception ex) {
             ex.printStackTrace();
        }
        return products;
    }

}
